package com.example.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class Database {
    private static final  String DATABASE_NAME="data";
    private static final int DATABASE_VERSION=1;
    private static final String TABLE_NAME="user";
    private static final String ID="_id";
    private static final String USERNAME="username";
    private static final String PASSWORD="password";
    private DBOpenHelper helper;
    private SQLiteDatabase db;
    private  class DBOpenHelper extends SQLiteOpenHelper {

        private static final String CREATE_TABLE="create table "+TABLE_NAME+"("+USERNAME +" text not null, "+PASSWORD+ " text not null); ";
        public DBOpenHelper(Context context) {
            super(context,DATABASE_NAME ,null,DATABASE_VERSION );
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_TABLE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("drop table if exists "+TABLE_NAME);
            onCreate(db);
        }
    }
    public Database(Context context){
        helper=new DBOpenHelper(context);
        db=helper.getWritableDatabase();
    }
    public void insert(User user){
        ContentValues values=new ContentValues();
        values.put(USERNAME,user.getUsername());
        values.put(PASSWORD,user.getPassword());
        db.insert(TABLE_NAME,null,values);
    }

    public User query(String name){
        User user=new User();
        Cursor cursor=db.query(TABLE_NAME,new String[]{USERNAME,PASSWORD},"username=?",new String[]{name},null,null,null);
        if (cursor.getCount()>0){
            cursor.moveToFirst();
            user.setUsername(cursor.getString(0));
            user.setPassword(cursor.getString(1));
            return user;
        } else if (cursor.getCount()<=0) {
            user.setUsername("");
            user.setPassword("");
            return user;
        }

        cursor.close();
        return null;
    }
}
